package com.cxyjy.travelguide.controller;

import com.cxyjy.common.util.JFileUtil;
import com.cxyjy.common.util.JResponse;
import com.cxyjy.common.util.ResultUtil;
import com.cxyjy.travelguide.service.ImageMatchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import static com.cxyjy.common.constants.CfyuiConstants.BAIDU_EXPECTED_IMAGE_EXTENSIONS;
import static com.cxyjy.common.util.ResultCode.FACESWAP_EXCLUSIVE_PARAMETERS_PROVIDED;
import static com.cxyjy.common.util.ResultCode.NO_IMAGE_FOUNDED;

/**
 * @Author: jony
 * @Date : 2025/4/17 16:16
 * @VERSION v1.0
 */
@RestController
public class ImageMatchController {
    @Autowired
    ImageMatchService imageMatchService;

    public JResponse createTemplateImage(MultipartFile multipartFile) {
        return null;
    }


    /**
     * 图片比对接口，image为图片文件，url为图片url，只能二选一，并且根据城市id和景区id筛选，limit为最后限制输出的条数
     * @param image
     * @param url
     * @param limit    限制最后返回的相似文物数量
     * @param classId1 城市id(1~999)
     * @param classId2 景区id(999~65535)
     * @return
     * @throws Exception
     */
    @PostMapping("/matchImage")
    public JResponse matchImage(@RequestParam(required = false) MultipartFile image,
                                @RequestParam(required = false) String url,
                                @RequestParam(defaultValue = "3") int limit,
                                @RequestParam(required = false) String classId1,
                                @RequestParam(required = false) String classId2
    ) throws Exception {
        //二选一校验：必须传image或url，且不能同时传
        if ((image == null && url == null) || (image != null && url != null)) {
            return ResultUtil.error(FACESWAP_EXCLUSIVE_PARAMETERS_PROVIDED);
        }
        if (image != null) {
            if (image.isEmpty() || image.getOriginalFilename() == null) {
                return ResultUtil.error(NO_IMAGE_FOUNDED);
            }
            if (!JFileUtil.checkFileExtension(image, BAIDU_EXPECTED_IMAGE_EXTENSIONS)) {
                return ResultUtil.error(NO_IMAGE_FOUNDED);
            }
        }
        String tags;
        if (classId1 == null && classId2 == null) {
            tags = null;
        } else if (classId1 == null) {
            tags = classId2;
        } else if (classId2 == null) {
            tags = classId1;
        } else {
            tags = classId1 + "," + classId2;
        }
        return image != null ? imageMatchService.matchImage(image, tags, limit) : imageMatchService.matchImage(url, tags, limit);
    }
}
